package main

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/mvcc/mvccpb"
	"time"
)

func main() {
	var (
		config        clientv3.Config
		client        *clientv3.Client
		err           error
		kv            clientv3.KV
		watcher       clientv3.Watcher
		getResp       *clientv3.GetResponse
		startRevision int64
		watchChanResp clientv3.WatchChan
	)

	config = clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
	}

	if client, err = clientv3.New(config); err != nil {
		fmt.Println(err)
		return
	}

	kv = clientv3.NewKV(client)
	go func() {
		for {
			kv.Put(context.TODO(), "/cron/jobs/job10", "{...}")

			kv.Delete(context.TODO(), "/cron/jobs/job10")

			time.Sleep(1 * time.Second)
		}
	}()

	watcher = clientv3.NewWatcher(client)
	if getResp, err = kv.Get(context.TODO(), "/cron/jobs/job10"); err != nil {
		fmt.Println(err)
	}

	startRevision = getResp.Header.Revision + 1
	watchChanResp = watcher.Watch(context.TODO(), "/cron/jobs/job10", clientv3.WithRev(startRevision))

	for val := range watchChanResp {
		for _, v := range val.Events {
			switch v.Type {
			case mvccpb.PUT:
				fmt.Println("更新为: ", v.Kv)
			case mvccpb.DELETE:
				fmt.Println("删除: ", v.Kv)
			}
		}
	}

}
